from flask import Flask, views, request, jsonify
import requests, json, time, warnings
from elasticsearch import Elasticsearch
from flask_sqlalchemy import SQLAlchemy

# import consul
app = Flask(__name__)

# 加载配置文件
app.config.from_object("config")
# 处理中文编码
app.config['JSON_AS_ASCII'] = False
# 实例化数据库
db = SQLAlchemy(app)
# 连接es
es = Elasticsearch([{"host": app.config['ESHOST'], "port": app.config['ESPORT'], "timeout": 5}])
# 忽略警告
warnings.filterwarnings("ignore")

from core.utils.log_helper import logger


class RegistrationInfoTB(db.Model):

    __tablename__ = 'register_db'


    id = db.Column(db.Integer, primary_key=True)
    RegistrationID = db.Column(db.String(80), nullable=False, unique=True)
    HgSystemAbridge = db.Column(db.String(80), nullable=False)
    DevelopersAbridge = db.Column(db.String(80), nullable=False)
    CustomerAbridge = db.Column(db.String(80), nullable=True)
    ProductionOrTest = db.Column(db.String(80), nullable=False)
    InputJson = db.Column(db.String(500), nullable=False)
    Auto = db.Column(db.Boolean, nullable=True, default=False)
    Text1 = db.Column(db.String(500), nullable=True)
    Text2 = db.Column(db.String(500), nullable=True)

    def __repr__(self):
        return '{},{},{},{},{},{},{},{},{}'.format(self.id, self.RegistrationID, self.HgSystemAbridge,
                                                   self.DevelopersAbridge, self.CustomerAbridge, self.ProductionOrTest,
                                                   self.InputJson, self.Auto, self.Text1, self.Text2)


# 1.创建表
# db.drop_all()
db.create_all()


# admin = RegistrationInfoTB(RegistrationID='admin3', HgSystemAbridge='1001',DevelopersAbridge='1231',CustomerAbridge='1234567891',ProductionOrTest='1',InputJson='1')
# db.session.add(admin)
# db.session.commit()
# print(RegistrationInfoTB.query.all(),'/////')
# for t in db.metadata.sorted_tables:
#             print("tablename",t.name)


class UF_GetFileInfo(views.MethodView):
    def __init__(self):
        # es日志索引
        self.index = 'yd_register'

    # 返回值封装
    def _render(self, code=None, msg=None):

        logger.error("返回值：错误代码：%s,错误信息：%s" % (code, msg))

        return jsonify({
            'code': code,
            'msg': msg
        })

    # 封装输入到es的函数
    def LogToElastic(self, index, info):
        time_ = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        es.index(index=index, body={"msg": f"{time_} - - - - - - - - - - - - - {info}"})

    def get(self):

        # self.LogToElastic(self.index,"get请求了/api/UF_NewRegistration,但此接口仅支持post")
        return self._render(-720, '注册请求方式仅限为POST')

    def post(self):
        try:
            # self.LogToElastic(self.index, "post请求了/api/UF_NewRegistration")
            result = request.form
            InputJson_res = result.get('InputJson', '')
            if not InputJson_res:
                return self._render(-721, '未传入参数InputJson,请检查重试')
            else:
                res = json.loads(InputJson_res)
                HgSystemAbridge = res.get("HgSystemAbridge", '')  # 异构系统英文缩写
                DevelopersAbridge = res.get("DevelopersAbridge", '')  # 开发商英文缩写
                CustomerAbridge = res.get("CustomerAbridge", '')  # 客户英文缩写
                ProductionOrTest = res.get("ProductionOrTest", '')  # 生产/测试环境
                if not HgSystemAbridge:
                    return self._render(-722, 'HgSystemAbridge参数传递错误,请检查重试')
                elif not DevelopersAbridge:
                    return self._render(-729, 'DevelopersAbridge参数传递错误,请检查重试')
                elif not CustomerAbridge:
                    return self._render(-730, 'CustomerAbridge参数传递错误,请检查重试')
                elif not ProductionOrTest:
                    return self._render(-731, 'ProductionOrTest参数传递错误,请检查重试')


                else:
                    try:
                        # 查询是否已注册逻辑
                        results = RegistrationInfoTB.query.filter_by(HgSystemAbridge=HgSystemAbridge,
                                                                     DevelopersAbridge=DevelopersAbridge,
                                                                     CustomerAbridge=CustomerAbridge,
                                                                     ProductionOrTest=ProductionOrTest).first()

                        # 传入参数，记录日志
                        logger.info(
                            "传入参数：HgSystemAbridge:%s, DevelopersAbridge:%s, CustomerAbridge:%s, ProductionOrTest:%s" % (
                                HgSystemAbridge, DevelopersAbridge, CustomerAbridge, ProductionOrTest))
                        print(results, 'results')

                        if results:
                            # if results:
                            #     DevelopersAbridgeres = results.DevelopersAbridge
                            #     CustomerAbridgeres = results.CustomerAbridge
                            #     ProductionOrTestres = results.ProductionOrTest
                            RegistrationID = results.RegistrationID
                            #     print(DevelopersAbridgeres,CustomerAbridgeres,ProductionOrTestres)
                            #     if DevelopersAbridgeres ==DevelopersAbridge and CustomerAbridgeres ==CustomerAbridge and ProductionOrTestres==ProductionOrTest:
                            #         RegistrationID = RegistrationIDres
                            logger.info("返回信息：%s" % json.dumps({
                                "Errcode": 1,
                                "msg": "已注册过啦",
                                "RegistrationID": RegistrationID
                            }, ensure_ascii=False))
                            return jsonify({
                                "Errcode": 1,
                                "msg": "已注册过啦",
                                "RegistrationID": RegistrationID
                            })
                        #     else:
                        #
                        else:

                            data = {
                                "HgSystemAbridge": HgSystemAbridge,
                                "DevelopersAbridge": DevelopersAbridge,
                                "CustomerAbridge": CustomerAbridge,
                                "ProductionOrTest": ProductionOrTest,
                            }
                            # 调用内部接口获取注册id
                            url = f"http://{app.config['REGISTERHOST']}:{app.config['REGISTERPORT']}/api/OF_GetRegistrationID"
                            res = requests.post(url, data)
                            # 获取RegistrationID
                            print(res.text)
                            resjson = json.loads(res.text)
                            Errcode = resjson['Errcode']
                            if Errcode == 1:
                                RegistrationID = resjson['RegistrationID']
                                try:
                                    admin = RegistrationInfoTB(RegistrationID=RegistrationID,
                                                               HgSystemAbridge=HgSystemAbridge,
                                                               DevelopersAbridge=DevelopersAbridge,
                                                               CustomerAbridge=CustomerAbridge,
                                                               ProductionOrTest=ProductionOrTest,
                                                               InputJson=InputJson_res)
                                    db.session.add(admin)
                                    db.session.commit()


                                except Exception as e:
                                    logger.exception("-734, '数据库存入失败': %s" % e)
                                    return self._render(-734, '数据库存入失败')
                                else:

                                    logger.info("外部接口返回信息：%s" % json.dumps({
                                        "Errcode": 1,
                                        "msg": "",
                                        "RegistrationID": RegistrationID
                                    }, ensure_ascii=False))

                                    return jsonify({
                                        "Errcode": 1,
                                        "msg": "",
                                        "RegistrationID": RegistrationID
                                    })
                            else:
                                return jsonify(resjson)


                    except  Exception as e:
                        logger.exception("内部生成注册id错误,请重试 : %s" % e)
                        # self.LogToElastic(self.index, "调用内部生成RegistrationID接口失败")
                        return self._render(-725, '内部生成注册id错误,请重试')
        except Exception as e:
            logger.exception('内部错误:%s' % e)
            return self._render(-732, '内部错误')


app.add_url_rule('/api/UF_GetFileInfo', view_func=UF_GetFileInfo.as_view('UF_GetFileInfo'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=app.config['REGISTERPORT'])
